package 网络编程.网络聊天室;

import java.io.*;
import java.net.Socket;
import java.util.Properties;

public class serverMyRun implements Runnable{
    Socket socket;
    Properties prop;
    public serverMyRun(Socket socket,Properties pp){
        this.socket=socket;
        this.prop=pp;
    };
    @Override
    public void run() {
        //获取用户的选择
        try {

            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (true) {
                String choose = br.readLine();
                System.out.println(choose);
                switch (choose){
                    case "login"->login(br);
                    case "register"-> register(br);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void register(BufferedReader br) {
        System.out.println("用户选择了注册");
    }

    public  void login(BufferedReader br) throws IOException {
        System.out.println("用户选择了登录的操作");
        String userInf = br.readLine();
        String[] split = userInf.split("&");
        String user = split[0].split("=")[1];
        String password = split[1].split("=")[1];
        System.out.println("用户的用户名:"+user+"密码:"+password);
        //判断用户是否存在
        if (prop.containsKey(user)){
            //用户名存在继续判断密码
            if (prop.get(user).equals(password)){
                //返回用户登录成功
                writCountry("2");
                //把这个用户的socket加入到用户集合中
                server.arrSocketList.add(socket);
                //开始聊天
                tallCountry(br,user);
            }else {
                //用户密码输入错误
                System.out.println("用户密码输入错误");
                writCountry("1");
            }
        }else {
            //用户用户名不存在
            System.out.println("用户用户名不存在");
            writCountry("0");
        }

    }

    //定义一个方法,向所有的客户发送信息
    public  void tallCountry(BufferedReader br,String user) throws IOException {
        while (true){
            String data = br.readLine();
            System.out.println(user+":"+data);
            //进行群发
            for (Socket s : server.arrSocketList) {
                writCountry(s,user+":"+data);
            }
        }
    }


    //定义一个方法给客户端发送信息
    public void writCountry(String menssage) throws IOException {
        //获取输出流--此处获取的是开始链接的时候的链接的客户
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(menssage);
        bw.newLine();
        bw.flush();
    }

    //定义一个发送给指定客户的方法
    public void writCountry(Socket socket,String menssage) throws IOException {
        //此处的socket发送给的就是传入的socket的客户
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(menssage);
        //添加换行
        bw.newLine();
        bw.flush();
    }
}
